package org.example;

import java.util.concurrent.*;

public class TicketSeller1 {

    // 票的总数
    private static int totalTickets = 50;

    public static void main(String[] args) {
        // 创建一个自定义线程池
        int corePoolSize = 2; // 核心线程数
        int maximumPoolSize = 5; // 最大线程数
        long keepAliveTime = 60; // 空闲线程存活时间，单位秒

        // 创建线程池
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(),
                new ThreadPoolExecutor.CallerRunsPolicy() // 如果线程池满了，调用线程会直接执行任务
        );

        // 创建三个售票员任务
        for (int i = 0; i < 3; i++) {
            executorService.submit(new TicketTask());
        }

        // 关闭线程池
        executorService.shutdown();
    }

    // 售票任务
    static class TicketTask implements Runnable {
        @Override
        public void run() {
            // 售票员不断卖票直到票卖完
            while (true) {
                synchronized (TicketTask.class) {
                    if (totalTickets > 0) {
                        // 模拟售票操作
                        System.out.println(Thread.currentThread().getName() + " 售出第 " + (51 - totalTickets) + " 张票");
                        totalTickets--;
                        try {
                            // 模拟售票的延迟
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    } else {
                        break; // 如果没有票了，退出
                    }
                }
            }
        }
    }
}
